import os

import pymysql

import logging as log

from common.conf import Conf


def read_sqls(*sqlfiles):  # 读指定的sql文件sqlfile将所有有效sql语句存入列表并返回；如果不给参数则读取当前文件夹中所有sql文件中的sql语句
    try:
        if not sqlfiles:  # 没给参数
            sqlfiles = [i for i in os.listdir('../initsqls/') if i.endswith('.sql')]
    # print(sqlfiles)
        sqls = []
    # 否则，sqlfiles中本来就存着很多文件名
        for sfile in sqlfiles:
            file = open('../initsqls/'+sfile, 'r', encoding='utf-8')
            for sql in file:
                if sql.strip() and not sql.startswith('--'):
                     sqls.append(sql.strip())
        log.info(f'读sql语句文件{sqlfiles}成功')
        return sqls
    except BaseException as e:
        log.error('读sql语句文件出错==错误类型：{type(e).__name__}==错误内容：{e}')
        exit()


class DB:  # 构造方法，用于连接数据库，将数据库连接对象和游标存入私有成员变量
    def __init__(self):  # 构造方法
        try:
            dbinfo = Conf().dbinfo
            self.__conn = pymysql.connect(**dbinfo)
            self.__cursor = self.__conn.cursor()
            log.info(f'连接数据库{dbinfo}成功')
        except BaseException as e:
            log.error(f'连接数据库出错==错误类型：{type(e).__name__}==错误内容：{e}')
            exit()

    def init_db(self, *sqlfiles):  # 初始化数据库
        try:
            sqls = read_sqls(*sqlfiles)
            # print(sqls)
            for sql in sqls:
                self.__cursor.execute(sql)
            self.__conn.commit()
            log.info(f'初始化数据库{sqlfiles}成功')
        except BaseException as e:
            log.error(f'初始化数据库出错==错误类型：{type(e).__name__}==错误内容：{e}')
            exit()

    def checkdb(self, case_info, args, check_sql, expect_rows):  # 落库检查
        try:
            self.__cursor.execute(check_sql)
            actual_rows = self.__cursor.fetchone()[0]
            if actual_rows == expect_rows:
                log.info(f'{case_info}==落库检查通过')
                passed=True  #表示测试通过
                msg=''   #成功时不需要断言消息
            else:
                msg=f'{case_info}==落库检查失败==要检查的数据：{args}==预期行数：{expect_rows}==实际行数：{actual_rows}'#失败时需要断言消息
                log.warning(msg)
                passed=False  #表示测试失败
                self.__conn.close()
                return passed,msg
        except BaseException as e:
            log.error(f'落库检查出错==错误类型：{type(e).__name__}==错误内容：{e}')
            exit()


if __name__ == '__main__':
    # print(read_sqls('login.sql'))
    # DB().init_db('signup.sql')
    DB().checkdb('总行数',{'a':1},'select count(*) from users',6)


 
